﻿using FastReport.Barcode;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.DataEntify;
using LanDBom.Controllers;
using LanDBom.Models;
using LanDBom.Models.Algorithm;
using LanDBom.Models.price_New_2;
using LanDBom.Models.Procure;
using Microsoft.Office.Interop.Excel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace LanDBom.Views.Cuobaojia
{
    public class CuobaojiaController : Controller
    {
        // GET: Cuobaojia
        Get_CL get_cl = new Get_CL();
        Get_CL_sho GCS = new Get_CL_sho();
        //Application application = new Application();
        Find_ShoTJ shoTJ = new Find_ShoTJ();
        LDbaseEntities db = new LDbaseEntities();
        Find_BOMini mini = new Find_BOMini();
        Find_Libary Find_Libary = new Find_Libary();
        GY_Algorithm GY = new GY_Algorithm();
        JChelp chelp = new JChelp();
        Find_P FP = new Find_P();
        // GET: Application
        public ActionResult Application(int CL_ID = -99, int state = 0, string Name = "", string Named = "", int id = 0, string App_ban = "", string Nameed = "", string Lj = "", string husJI = "", string name = "", int DE_id = -99)
        {
            var listShoTJ = shoTJ.Get_ShoTJ();
            ViewBag.listShoTJ = listShoTJ;
            var listarea = get_cl.GetCL_name();
            ViewBag.lsitCL_name = listarea;
            var listsho = GCS.GetCinemaName(CL_ID);
            ViewBag.listsho = listsho;
            ViewBag.ic = db.IndustryCategory.ToList();
            ViewBag.JIliang = db.Freht.ToList();
            ViewBag.ZUI = db.jectsche.OrderBy(s => s.Je_hanghao).ToList();
            ViewBag.Shuai = Lj;
            ViewBag.temp2 = db.buty3.ToList();

            if (App_ban != "" && state == 0)
            {
                int num = db.Applications.Where(x => x.AP_bian == App_ban).FirstOrDefault().App_id;
                Session["appp_id"] = num;
                Session["JKO_ko"] = get_cl.JIDN(App_ban, Nameed);
                Session["name"] = name;
            }
            else
            {
                Session["appp_id"] = id;
                Session["name"] = "";
            }

            var shunji = db.Dengli.ToList();
            ViewBag.res = shunji;
            if (state == 1)
            {
                try
                {
                    List<Clirntele> cli = db.Clirntele.Where(s => s.CL_name.Contains(Name)).ToList();

                    //
                    //集成查询客户
                    var client = new K3CloudApi();
                    //用于记录结果
                    StringBuilder Info = new StringBuilder();
                    //业务对象标识
                    string formId = "BD_Customer";
                    string fieldKeys = "FName,FADDRESS,FEMail,FNumber";//客户 编码 联系电话 邮箱 通讯地址 备注 省份
                    string Filter = "FName like'%" + Name + "%'";
                    //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                    var param = new QueryParam()
                    {
                        FormId = formId,
                        FieldKeys = fieldKeys,
                        FilterString = Filter,
                        TopRowCount = 0,
                        StartRow = 0,
                        Limit = 20,
                    };
                    //调用接口
                    var result = client.ExecuteBillQuery(param.ToJson());


                    //返回的数据类型为List<List<object>>，错误的返回结果只有一行数据且IsSuccess为False
                    if (result.Count == 1)
                    {
                        //对返回结果进行解析和校验，这里使用的是JsonPatch
                        var resultJObject = JArray.Parse(JsonConvert.SerializeObject(result[0]));
                        var queryNode = resultJObject.SelectToken("$..IsSuccess");
                        if (queryNode != null)
                        {
                            var isSuccess = queryNode.Value<Boolean>();
                            Info.AppendLine(isSuccess ? "操作成功" : "操作失败");
                        }
                        else
                        {
                            ApplicationController.Jichengss(cli, result);
                            Info.AppendLine("操作成功");
                        }
                    }
                    else
                    {
                        ApplicationController.Jichengss(cli, result);
                        Info.AppendLine("操作成功");
                    }
                    var list = from s in cli select new { s.CL_name, s.CL_ju, s.CL_sho };//遍历出自己数据库的数据
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    string jsongStr = JsonConvert.SerializeObject(list, settings);

                    return Content(jsongStr, "application/json");
                }
                catch (Exception ex)
                {
                    var shu = ex.Message;
                    return Json(shu);
                }
            }
            if (state == 2)
            {
                try
                {
                    List<Formation> fom = new List<Formation>();
                    //计算集成
                    //
                    //集成查询客户
                    var client = new K3CloudApi();
                    //用于记录结果
                    StringBuilder Info = new StringBuilder();
                    //业务对象标识
                    string formId = "BD_MATERIAL";
                    string fieldKeys = "FNumber,FName,FSpecification,FErpClsID,FBaseUnitId.FNumber,FRefCost,FMaterialGroup.FNumber,FMaterialGroup.FName,FMATERIALID";//
                    string Filter = "FNumber like'" + Named + "%'and FDocumentStatus='C' and FForbidStatus='A' and FUseOrgId.FNumber='10.01' ";
                    //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                    var param = new QueryParam()
                    {
                        FormId = formId,
                        FieldKeys = fieldKeys,
                        FilterString = Filter,
                        TopRowCount = 0,
                        StartRow = 0,
                        Limit = 20,
                    };
                    //调用接口
                    var result = client.ExecuteBillQuery(param.ToJson());
                    //返回的数据类型为List<List<object>>，错误的返回结果只有一行数据且IsSuccess为False
                    if (result.Count == 1)
                    {
                        //对返回结果进行解析和校验，这里使用的是JsonPatch
                        var resultJObject = JArray.Parse(JsonConvert.SerializeObject(result[0]));
                        var queryNode = resultJObject.SelectToken("$..IsSuccess");
                        if (queryNode != null)
                        {
                            var isSuccess = queryNode.Value<Boolean>();
                            Info.AppendLine(isSuccess ? "操作成功" : "操作失败");
                        }
                        else
                        {
                            ApplicationController.Jichewuliao(fom, result);
                            Info.AppendLine("操作成功");
                        }
                    }
                    else
                    {
                        ApplicationController.Jichewuliao(fom, result);
                        Info.AppendLine("操作成功");
                    }
                    var list = from s in fom select new { s.FM_name, s.FM_bai, s.FM_long, s.FM_kuan, s.FM_gao, s.FM_ji, s.FM_Zhuang, s.FM_yj, s.FM_ej, s.FM_nyl, s.FM_gg };
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    string jsongStr = JsonConvert.SerializeObject(list, settings);
                    return Content(jsongStr, "application/json");
                }
                catch (Exception ex)
                {
                    string shdunngf = ex.Message;
                    return Json(shdunngf);
                }
            }
            if (state == 5)
            {
                var list = from s in listsho
                           select new { s.CL_sho };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);

                return Content(jsongStr, "application/json");
            }
            if (state == 9)
            {
                List<BOMin> bomin = db.BOMin.Where(a => a.App_bian == App_ban).ToList();
                var list = from s in bomin select new { s.BOM_name, s.Bom_chen, s.BOM_guige, s.BOM_liao, s.BOM_lei, s.BOM_nian, s.BOM_ji, s.BOM_yong };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);

                return Content(jsongStr, "application/json");
            }
            if (state == 10)
            {
                var ERP = db.Applications.Where(s => s.AP_bian.Contains("ERP")).OrderByDescending(s => s.App_id).ToList();
                var diyi = ERP[0].App_id;
                diyi++;
               
                var bian = "ERP" + diyi.ToString();
                var shunf = db.Applications.Where(s => s.AP_bian == bian).FirstOrDefault();
                if (shunf != null)
                {
                    diyi++;
                    bian = "ERP" + diyi.ToString();
                }
                return Content(bian);
            }
            return View();

        }


        public ActionResult AddApplication(Applications applications)
        {
            var bian = applications.AP_bian;
            var index = db.Applications.Where(x => x.AP_bian == bian).FirstOrDefault();
            //编码是按循序排列 避免人员保存时产生冲突 根据人员判断是否需要重新生成编码
            var BiM = "";
            if (index == null)
            {
                db.Applications.Add(applications);
                int rows = db.SaveChanges();
                var JIkn = applications.AP_bian;
                var shun = 0;
                using (LDbaseEntities db11 = new LDbaseEntities())
                {
                    shun = db11.Applications.Where(s => s.AP_bian == JIkn).FirstOrDefault().App_id;
                }
                var hu = JIkn + "+" + shun;
                string message = rows > 0 ? hu : "添加失败";
                return Content(message, "text / plain");
            }
            if (index != null)
            {
                if (applications.AP_ren != index.AP_ren)
                {
                    using (LDbaseEntities LD = new LDbaseEntities())
                    {
                        var ERP = LD.Applications.Where(s => s.AP_bian.Contains("ERP")).OrderByDescending(s => s.App_id).ToList();
                        var diyi = ERP[0].App_id;
                        diyi++;

                        BiM = "ERP" + diyi.ToString();
                        var shunf = LD.Applications.Where(s => s.AP_bian == BiM).FirstOrDefault();
                        if (shunf != null)
                        {
                            diyi += 10;
                            BiM = "ERP" + diyi.ToString();
                        }
                    }
                    applications.AP_bian = BiM;
                    db.Applications.Add(applications);
                    int rows = db.SaveChanges();
                    var shun = 0;
                    using (LDbaseEntities db11 = new LDbaseEntities())
                    {
                        shun = db11.Applications.Where(s => s.AP_bian == BiM).FirstOrDefault().App_id;
                    }
                    var hu = BiM + "+" + shun;
                    string message = rows > 0 ? hu : "添加失败";
                    return Content(message, "text / plain");
                }
                else
                {
                    index.AP_ren = applications.AP_ren;
                    index.App_qishi = applications.App_qishi;
                    index.App_bu = applications.App_bu;
                    index.App_BanB = applications.App_BanB;
                    index.App_bei = applications.App_bei;
                    db.Entry(index).State = EntityState.Modified;
                    int rhu = db.SaveChanges();
                    var bianshu = applications.AP_bian + "+" + index.App_id;
                    string mess = rhu > 0 ? bianshu : "添加失败";
                    return Content(mess, "text / plain");
                }
            }
            return View();
        }

        //添加BOM或物料信息
        [HttpPost]
        public JsonResult AddAppli(List<BOMini> bOMinis)
        {
            //二级标识
            char[] letter = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
            if (bOMinis == null)
            {
                bOMinis = new List<BOMini>();
            }
            var st = 0;
            var hdfu = "";
            for (int i = 0; i < bOMinis.Count; i++)
            {
                if (bOMinis[i].BOM2_chen == "Leve0")
                {
                    var aed = bOMinis[i].BOM2_bian;
                    var vf = bOMinis[i].BOM2_wuLiu;
                    hdfu = bOMinis[i].BOM2_BQing;
                    bOMinis[i].BOM2_BQing = hdfu;
                }
                if (bOMinis[i].BOM2_chen == "leve1")
                {
                    bOMinis[i].BOM2_BQing = hdfu + "-" + letter[st].ToString();
                    st++;
                }
                if (bOMinis[i].BOM2_chen == "leve2")
                {
                    if (bOMinis[i - 1].BOM2_chen == "leve1")
                    {
                        bOMinis[i].BOM2_BQing = bOMinis[i - 1].BOM2_BQing + "-a";
                    }
                    if (bOMinis[i - 1].BOM2_chen == "leve2")
                    {
                        bOMinis[i].BOM2_BQing = bOMinis[i - 1].BOM2_BQing;
                    }
                }
            }

            foreach (BOMini b in bOMinis)
            {
                //取banb
                var appect = b.BOM2_bian;
                var app = db.Applications.FirstOrDefault(s => s.AP_bian == appect);
                int wuliao = (from s in db.Formation where s.FM_bai == b.BOM2_liao select s.FM_ID).FirstOrDefault();/*获取formationde id 信息*/
                var appid = db.Formation.Where(s => s.FM_ID == wuliao).FirstOrDefault();/*获取formationde 料号信息*/
                //进行赋值 添加id的值
                b.Fo_id = null;
                if (wuliao > 0)
                {
                    b.Fo_id = wuliao;
                }
                if (appid != null)
                {
                    b.BOM2_liao = appid.FM_bai;
                    b.BOM2_fenzi = appid.FM_ji;
                }
                b.BOM2_Zhuang = app.App_BanB;
                var hunji = b.BOM2_BQing;
                var A = b.BOM2_bian;
                var h = db.BOMini.Where(s => s.BOM2_BQing == hunji && s.BOM2_bian == A).FirstOrDefault();///判断该条是否存在
                if (h != null)
                {
                    h.BOM2_wuLiu = b.BOM2_wuLiu;
                    h.BOM2_liao = b.BOM2_liao;
                    h.BOM2_duan = b.BOM2_duan;
                    h.BOM2_Guige = b.BOM2_Guige;
                    h.BOM2_Nian = b.BOM2_Nian;
                    h.BOM2_Yong = b.BOM2_Yong;
                    h.BOM2_fenzi = b.BOM2_fenzi;
                    h.BOM2_Lei = b.BOM2_Lei;
                    h.BOM2_Sone = b.BOM2_Sone;
                    h.BOM2_ST = b.BOM2_ST;
                    db.Entry(h).State = EntityState.Modified;
                }
                else
                {
                    db.BOMini.Add(b);
                }
            }
            int sun = db.SaveChanges();
            foreach (BOMini b in bOMinis)
            {
                var bian = b.BOM2_liao;
                var BK = db.Formation.Where(s => s.FM_bai == bian).FirstOrDefault();
                if (BK == null)
                {
                    var zzbds = new Regex(@"\d+(\.\d+)?");
                    var Gui = b.BOM2_Guige.Split('*');
                    var temp7 = b.BOM2_Sone;
                    var skn = temp7 == "1" ? "纸质" : temp7 == "2" ? "木质" : temp7 == "3" ? "塑料" : temp7 == "4" ? "金属制品" : temp7 == "5" ? "布" : temp7 == "6" ? "胶粘制品" : temp7 == "7" ? "其他" : temp7 == "8" ? "套件" : temp7;
                    var shudn = new Formation
                    {
                        FM_bai = b.BOM2_liao,
                        FM_name = b.BOM2_wuLiu,
                        FM_ji = b.BOM2_fenzi,
                        FM_gg = b.BOM2_Guige,
                        FM_yj = skn,
                        FM_ej = b.BOM2_ST,
                        FM_Zhuang = b.BOM2_Lei,
                        FM_long = Gui.Length > 1 ? (decimal?)double.Parse(zzbds.Match(Gui[0]).ToString()) : 0,
                        FM_kuan = Gui.Length > 1 ? (decimal?)double.Parse(zzbds.Match(Gui[1]).ToString()) : 0,
                        FM_gao = Gui.Length > 2 ? (decimal?)double.Parse(zzbds.Match(Gui[2]).ToString()) : 0,
                    };
                    db.Formation.Add(shudn);
                }
                else
                {
                    if (b.BOM2_Guige == null || b.BOM2_Guige == "")
                    {
                        b.BOM2_Guige = "0*0*0";
                    }
                    var zzbds = new Regex(@"\d+(\.\d+)?");
                    var Gui = b.BOM2_Guige.Split('*');
                    var temp7 = b.BOM2_Sone;
                    var skn = temp7 == "1" ? "纸制品" : temp7 == "2" ? "木质" : temp7 == "3" ? "塑料制品" : temp7 == "4" ? "金属制品" : temp7 == "5" ? "布" : temp7 == "6" ? "胶粘制品" : temp7 == "7" ? "其他" : temp7 == "8" ? "套件" : temp7;
                    BK.FM_bai = b.BOM2_liao;
                    BK.FM_name = b.BOM2_wuLiu;
                    BK.FM_ji = b.BOM2_fenzi;
                    BK.FM_gg = b.BOM2_Guige;
                    BK.FM_yj = skn;
                    BK.FM_ej = b.BOM2_ST;
                    BK.FM_Zhuang = b.BOM2_Lei;
                    BK.FM_long = Gui.Length > 1 ? (decimal?)double.Parse(zzbds.Match(Gui[0]).ToString()) : 0;
                    BK.FM_kuan = Gui.Length > 1 ? (decimal?)double.Parse(zzbds.Match(Gui[1]).ToString()) : 0;
                    BK.FM_gao = Gui.Length > 2 ? (decimal?)double.Parse(zzbds.Match(Gui[2]).ToString()) : 0;
                    db.Entry(BK).State = EntityState.Modified;
                    int jkmj= db.SaveChanges();
                }
            }
            int sun2e = db.SaveChanges();
            return Json(sun);

        }

        //添加BOM
        public ActionResult Boms(string names, string bina = "", string binaed = "", string hudnf = "", int state = 0)
        {
            if (names == null)
            {
                names = "-1";
            }
            if (state == 1)
            {
                List<BOMini> bOMinis = db.BOMini.Where(s => s.BOM2_bian == bina).ToList();
                var list = from a in bOMinis select new { a.BOM2_chen, a.BOM2_Nian, a.BOM2_liao, a.BOM2_duan, a.BOM2_bian, a.BOM2_wuLiu, a.BOM2_Yong, a.BOM2_sunhao, a.BOM2_Lei, a.BOM2_Ctime, a.BOM2_mioa };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            if (state == 3)
            {
                List<BOMini> bominis = db.BOMini.ToList();
                List<BOMini> bOMinis = db.BOMini.Where(s => s.BOM2_bian == hudnf && s.BOM2_BQing.Contains(binaed)).ToList();
                var list = from a in bOMinis select new { a.BOM2_chen, a.BOM2_Nian, a.BOM2_liao, a.BOM2_duan, a.BOM2_bian, a.BOM2_wuLiu, a.BOM2_Yong, a.BOM2_sunhao, a.BOM2_Lei, a.BOM2_Ctime, a.BOM2_mioa, a.BOM2_Guige, /*BOM2_Sone = a.BOM2_Sone == "1" ? "纸制品" : a.BOM2_Sone == "2" ? "木制品" : a.BOM2_Sone == "3" ? "塑料制品" : "", a.BOM2_ST*/ };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            if (state == 4)
            {
                Applications app = db.Applications.Where(a => a.AP_bian == binaed).FirstOrDefault();
                app.App_bu = "3";
                int row = db.SaveChanges();
                string messsage = row > 0 ? "1" : "0";
                return Content(messsage, "application/json");
            }
            //names = "SQ202311136225661";
            var applications = db.Applications.Where(s => s.AP_bian == names).ToList();
            var snif = db.Applications.Where(r => r.AP_bian == names).FirstOrDefault();
            var hdns = snif.App_BanB;
            List<BOMini> bOMins = db.BOMini.Where(s => s.BOM2_bian == names && s.BOM2_chen == "Leve0" && s.BOM2_Zhuang == hdns).ToList();
            var shnf = db.JiCheng.FirstOrDefault(s => s.JC_bianhao == names && s.JC_zhuang != "已删除");
            ViewBag.fhishf = bOMins;
            ViewBag.JIliang = db.Freht.ToList();
            ViewBag.ZUI = db.jectsche.OrderBy(s => s.Je_hanghao).ToList();
            ViewBag.ic = db.IndustryCategory.ToList();
            ViewBag.temp2 = db.buty3.ToList();
            Session["JC_zhuang"] = shnf == null ? null : shnf.JC_zhuang;
            return View(applications);
        }
        public ActionResult Bosin(string Name = "", int state = 0)
        {
            if (state == 1)
            {
                try
                {
                    List<Formation> fom = db.Formation.Where(s => s.FM_name.Contains(Name)).ToList();
                    //计算集成
                    //
                    //集成查询客户
                    var client = new K3CloudApi();
                    //用于记录结果
                    StringBuilder Info = new StringBuilder();
                    //业务对象标识
                    string formId = "BD_MATERIAL";
                    string fieldKeys = "FNumber,FName,FSpecification,FErpClsID,FBaseUnitId.FNumber,FRefCost";//名称 编码 规格 采购属性 单位 价格
                    string Filter = "FName like'%" + Name + "%'";
                    //请求参数，示例使用的是SDK提供的模板类，还可以使用字符串拼接等方式
                    var param = new QueryParam()
                    {
                        FormId = formId,
                        FieldKeys = fieldKeys,
                        FilterString = Filter,
                        TopRowCount = 0,
                        StartRow = 0,
                        Limit = 20,
                    };
                    //调用接口
                    var result = client.ExecuteBillQuery(param.ToJson());
                    //返回的数据类型为List<List<object>>，错误的返回结果只有一行数据且IsSuccess为False
                    if (result.Count == 1)
                    {
                        //对返回结果进行解析和校验，这里使用的是JsonPatch
                        var resultJObject = JArray.Parse(JsonConvert.SerializeObject(result[0]));
                        var queryNode = resultJObject.SelectToken("$..IsSuccess");
                        if (queryNode != null)
                        {
                            var isSuccess = queryNode.Value<Boolean>();
                            Info.AppendLine(isSuccess ? "操作成功" : "操作失败");
                        }
                        else
                        {
                            ApplicationController.Jichewuliao(fom, result);
                            Info.AppendLine("操作成功");
                        }
                    }
                    else
                    {
                        ApplicationController.Jichewuliao(fom, result);
                        Info.AppendLine("操作成功");
                    }
                    var list = from s in fom select new { s.FM_name, s.FM_bai, s.FM_long, s.FM_kuan, s.FM_gao, s.FM_ji, s.FM_Zhuang };
                    JsonSerializerSettings settings = new JsonSerializerSettings();
                    string jsongStr = JsonConvert.SerializeObject(list, settings);
                    return Content(jsongStr, "application/json");
                }
                catch (Exception ex)
                {
                    string shdunngf = ex.Message;
                    return Json(shdunngf);
                }
            }
            return View();
        }
        //BOM录入数据库
        [HttpPost]
        public JsonResult AddBoms(List<BOMini> bOMinis)
        {
            //
            char[] letter = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
            if (bOMinis == null)
            {
                bOMinis = new List<BOMini>();
            }
            var st = 0;
            var hdfu = "";
            for (int i = 0; i < bOMinis.Count; i++)
            {
                if (bOMinis[i].BOM2_chen == "Leve0")
                {
                    var aed = bOMinis[i].BOM2_bian;
                    var vf = bOMinis[i].BOM2_wuLiu;
                    var hdfus = db.BOMini.FirstOrDefault(a => a.BOM2_chen == "Leve0" && a.BOM2_bian == aed && a.BOM2_wuLiu == vf);
                    hdfu = hdfus.BOM2_BQing;
                    bOMinis[i].BOM2_BQing = hdfu;
                }
                if (bOMinis[i].BOM2_chen == "leve1")
                {
                    bOMinis[i].BOM2_BQing = hdfu + "-" + letter[st].ToString();
                    st++;
                }
                if (bOMinis[i].BOM2_chen == "leve2")
                {
                    if (bOMinis[i - 1].BOM2_chen == "leve1")
                    {
                        bOMinis[i].BOM2_BQing = bOMinis[i - 1].BOM2_BQing + "-a";
                    }
                    if (bOMinis[i - 1].BOM2_chen == "leve2")
                    {
                        bOMinis[i].BOM2_BQing = bOMinis[i - 1].BOM2_BQing;
                    }
                }
            }

            foreach (BOMini b in bOMinis)
            {
                int wuliao = (from s in db.Formation where s.FM_name == b.BOM2_wuLiu select s.FM_ID).FirstOrDefault();/*获取formationde id 信息*/
                var appid = db.Formation.Where(s => s.FM_ID == wuliao).FirstOrDefault();/*获取formationde 料号信息*/
                var BOMbia = b.BOM2_bian;
                var app_bom = db.Applications.FirstOrDefault(s => s.AP_bian == BOMbia);
                //进行赋值 添加id的值
                if (wuliao > 0)
                {
                    b.Fo_id = wuliao;
                }
                else
                {
                    b.Fo_id = null;
                }
                var wsde = app_bom.App_BanB;
                b.BOM2_Zhuang = wsde;
                var hunji = b.BOM2_BQing;
                var A = b.BOM2_bian;
                var h = db.BOMini.Where(s => s.BOM2_BQing == hunji && s.BOM2_bian == A && s.BOM2_Zhuang == wsde).FirstOrDefault();///判断该条是否存在
                if (b.BOM2_chen == "Leve0")
                {
                    continue;
                }
                else if (h != null)
                {
                    h.BOM2_wuLiu = b.BOM2_wuLiu;
                    h.BOM2_liao = b.BOM2_liao;
                    h.BOM2_duan = b.BOM2_duan;
                    h.BOM2_Guige = b.BOM2_Guige;
                    h.BOM2_Nian = b.BOM2_Nian;
                    h.BOM2_Yong = b.BOM2_Yong;
                    h.BOM2_fenzi = b.BOM2_fenzi;
                    h.BOM2_Lei = b.BOM2_Lei;
                    db.Entry(h).State = EntityState.Modified;
                }
                else
                {
                    db.BOMini.Add(b);
                }
            }
            int sun = db.SaveChanges();
            return Json(sun);
        }
        ///工艺添加
        public ActionResult Index(string names, string BOM2_wuLiu = "", string BOM2_liao = "", string Ap_bian = "", string BOM2_id = "", int state = 0)
        {
            //names = "SQ202311219556113 ";
            if (names == null)
            {
                names = "-1";
            }
            List<Applications> xian = db.Applications.Where(a => a.AP_bian == names).ToList();/*查询客户*/
            /*遍历工艺库是工艺根据种类分类*/
            var Yinshua = db.libray.Where(s => s.ST_ID == 1 && s.LB_bai.Contains("BAM")).ToList();  //印刷
            ViewBag.Yinshua = Yinshua;  //传递到前台--印刷
            var jieshe = db.libray.Where(s => s.ST_ID == 21 && s.LB_bai.Contains("BAM")).ToList();  //结合
            ViewBag.jieshe = jieshe;  //传递到前台--结合
            var mujus = db.libray.Where(s => s.ST_ID == 22 && s.LB_bai.Contains("BAM")).ToList();  //模具
            ViewBag.mujus = mujus;  //传递到前台--模具
            var Biaomian = db.libray.Where(s => s.ST_ID == 2 && s.LB_bai.Contains("BAM")).ToList();  //表面处理
            ViewBag.Biaomian = Biaomian;  //传递到前台--模具
            var XIshu = db.libray.Where(s => s.ST_ID == 6 && s.LB_bai.Contains("BAM")).ToList();  //吸塑
            ViewBag.XIshu = XIshu;  //传递到前台--模具
            var ListZBxx = FP.find_lib();
            ViewBag.ListZBxx = ListZBxx;
            ViewBag.ListPP = FP.find_manufacturer();
            ViewBag.ListZL = FP.find_ZL_();
            ViewBag.ListPO = FP.find_projectprs();
            ViewBag.parice = FP.find_parices();

            var dhf = mini.B_findnext(BOM2_wuLiu, BOM2_liao, names);
            dhf = dhf.OrderBy(s => s.BOM2_BQing).ToList();
            ViewBag.F_kehu = xian;
            ViewBag.F_bom = dhf;
            //查找物料信息(模糊查询)
            if (state == 1)
            {
                var list = from a in dhf select new { a.BOM2_id, a.BOM2_chen, a.BOM2_duan, a.BOM2_liao, a.BOM2_wuLiu, a.BOM2_Nian, a.BOM2_Yong };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(list, settings);
                return Content(jsongStr, "application/json");
            }
            if (state == 2)
            {
                List<BOMini> sun = db.BOMini.Where(s => s.BOM2_bian == Ap_bian).ToList();
                var sjh = GY.Tprice(sun);

                Applications app = db.Applications.FirstOrDefault(s => s.AP_bian == Ap_bian);
                app.App_bu = "4";
                db.Entry<Applications>(app).State = EntityState.Modified;
                int aji = db.SaveChanges();
                string message = aji > 0 ? "修改成功" : "修改失败";
                return Content(message, "Material/Index");
            }
            if (state == 4)
            {
                var shunf = chelp.Shungdint(BOM2_id);
                return Content(shunf.ToString(), "application/json");
            }
            return View();
        }
        /*    /// //BOM添加工艺
            public ActionResult Addoperati(operational operat, Design design, string BOM2_id = "")
            {
                string message;
                try
                {
                    var bomin = db.BOMini.Find(int.Parse(BOM2_id));
                    var ren = db.Applications.Where(s => s.AP_bian == bomin.BOM2_bian).Select(s => s.AP_ren).FirstOrDefault();
                    //获取提交人
                    if (bomin.Fo_id == null)
                    {
                        bomin.Fo_id = null;
                    }
                    //计算费用
                    double Z_price = GY.Jiaoge(operat, BOM2_id);
                    //计算图纸数量----开始
                    string[] tuzhilei = { "客户图纸", "印刷图纸", "模切图纸" };
                    var shufn = design.De_dizhi.Split(';');
                    int shun = 0, hdjhf = 0;
                    for (int i = 0; i < shufn.Length; i++)
                    {
                        if (shufn[i] != "")
                        {
                            design.DE_tuiLei = tuzhilei[i];
                            design.BOM2_id = int.Parse(BOM2_id);
                            design.De_ren = ren;
                            design.De_shijian = DateTime.Now.ToString();
                            design.De_dizhi = shufn[i];
                            db.Entry(design).State = EntityState.Modified;
                            db.Design.Add(design);
                            shun += db.SaveChanges();
                        }
                        hdjhf++;
                    }
                    //计算图纸数量----结束
                    operat.OP_price = (decimal?)Z_price;
                    db.operational.Add(operat);
                    int mun = db.SaveChanges();
                    bomin.BOM2_Gong = operat.OP_ID;
                    //保存
                    db.Entry(bomin).State = EntityState.Modified;
                    int sun = db.SaveChanges();
                    if (sun == 1)
                    {
                        //判断是否关联成功
                        message = 1 > 0 ? "添加成功" : "添加失败";
                        return Content(message, "/Material/Index");
                    }
                    else
                    {
                        message = "系统错误";
                        return Content(message, "/Material/Index");
                    }

                }
                catch (Exception ex)
                {
                    message = "系统错误" + ex.Message;
                }
                return Content(message, "/Material/Index");
            }*/
        ///获取文件路径
        [HttpPost]
        public ActionResult SelectPath(int shu = 0)
        {
            try
            {
                var wenjainpath = GY.SelectwenPath();
                return Json(wenjainpath);
            }
            catch (Exception)
            {

                return Json(new
                {
                    Success = false,
                    Message = "系统错误！"
                });
            }
        }
        public ActionResult BomsView(string names, int state = 0, string BOM_Gong = "")
        {
            //names = "SQ202311136225661";
            if (names == null)
            {
                names = "-1";
            }
            List<Applications> app = db.Applications.Where(a => a.AP_bian == names).ToList();
            List<BOMini> bOs = db.BOMini.Where(a => a.BOM2_bian == names).OrderBy(s => s.BOM2_BQing).ToList();
            List<Formation> fo = db.Formation.ToList();
            List<Ndardo> nd = db.Ndardo.ToList();
            ViewBag.ListAPP = app;
            //计算总价
            double T_price = 0;
            if (state == 1)
            {
                //T_price = GY.Tprice(bOs);
                var lists = from a in bOs
                            join d in nd on a.BOM2_liao equals d.Fo_id into jtenm
                            from fgh in jtenm.DefaultIfEmpty()
                            select new { a.BOM2_Gong, a.BOM2_id, a.BOM2_chen, a.BOM2_wuLiu, a.BOM2_liao, a.BOM2_duan, a.BOM2_Nian, a.BOM2_Yong, a.BOM2_mioa, Nd_Gong = fgh == null ? "" : fgh.Nd_Gong, Nd_jiage = fgh == null ? 0 : fgh.Nd_jiage, Nd_danwei = fgh == null ? "" : fgh.Nd_danwei };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(lists, settings);
                Session["T_pricesed"] = T_price;
                return Content(jsongStr, "application/json");
            }

            //显示工艺功能
            if (state == 2)
            {
                int shu = -1;
                if (BOM_Gong != "" && BOM_Gong != "null" && BOM_Gong != null)
                {
                    shu = int.Parse(BOM_Gong);
                }
                List<operational> ope = db.operational.Where(a => a.OP_ID == shu).ToList();
                var lists = from a in ope select new { a.OP_ID, a.OP_Yin, a.OP_YinSe, a.OP_Muqie, a.OP_Muxinag, a.OP_biao, a.OP_Mujiu, a.OP_TIgong, a.OP_Wuli, a.OP_price };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(lists, settings);

                return Content(jsongStr, "application/json");
            }
            //显示图纸功能
            if (state == 3)
            {
                int shu = -1;
                if (BOM_Gong != "" && BOM_Gong != "null" && BOM_Gong != null)
                {
                    shu = int.Parse(BOM_Gong);
                }
                List<Design> ope = db.Design.Where(a => a.BOM2_id == shu).ToList();
                var lists = from a in ope select new { a.BOM2_id, a.DE_id, a.De_dizhi, a.DE_tuiLei, a.De_shijian, a.De_ren };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(lists, settings);

                return Content(jsongStr, "application/json");
            }
            return View();
        }

        //修改BOM价格
        public JsonResult Xiugai(List<BOMini> bOMinis)
        {
            if (bOMinis == null)
            {
                bOMinis = new List<BOMini>();
            }
            int nu = 0;
            var f = 0;
            foreach (var item in bOMinis)
            {
                var A = item.BOM2_id;
                BOMini b = db.BOMini.FirstOrDefault(s => s.BOM2_id == A);
                if (item.BOM2_chen == "Leve0")
                {

                    if (b.BOM2_mioa == item.BOM2_mioa)
                    {
                        nu++;
                    }
                    else
                    {
                        b.BOM2_mioa = item.BOM2_mioa;
                        nu += db.SaveChanges();
                    }
                    f++;
                }
            }

            string message = nu >= f ? "修改成功" : "修改失败";
            return Json(message);
        }
    }
}